(function() {
	var startBtn, endBtn;
	var startDate, endDate;
	var maxA, maxB, maxC;
	var quarterStr = '';
	var nightShap = '柱状图';
	var nightUnitShap = '(个)';
	var rankShap = '柱状图';
	var rankUnitShap = '(个)';
	var xAxisData = [];
	var yearNightData = []; //
	var holidayNightData = []; //
	var totalData = []; //
	var rankXData = []; //科室排名X轴数据
	var rankYData = []; //科室排名Y轴数据
	var lineChartEl;
	var rankChartEl;
	var titleStr = '';
	var isStaticRequest = false;
	var isRankRequest = false;
	var xmlStr,roles,maxRole,personID,wardID,nurseId,usercode;
	//tab2
	var locPage = 0,pageLimit = 30;
	var nurTypeStr = '';
	var xmlStr2;

	var active = 'tab1';

	mui.init();
	mui.plusReady(function() {
		mui('.mui-scroll-wrapper').scroll({
			indicators: false //是否显示滚动条
		});
		tabInitAndTapSetup(); //tabbar 切换方法
		var perInfo = app.getState()
		if(perInfo) {
			maxRole =  perInfo.maxRoleLevel||''
			roles = perInfo['loginRoleCodes']||''
			wardID = perInfo.loginWardId 
			personID = perInfo.loginPerID;
			nurseId = perInfo.loginID
			usercode = perInfo.usercode
		}
		baseSetup()
	})

	function tabInitAndTapSetup() {
		var tab1 = document.getElementById('tab1');
		var tab2 = document.getElementById('tab2');
		var tab1Content = document.getElementById('tab1Content');
		var tab2Content = document.getElementById('tab2Content');

		tab1.addEventListener('tap', function() {
			if(!tab1.classList.contains('mui-active')) {
				tab2Content.classList.remove('mui-active');
				tab2Content.style.display = 'none';
				tab1Content.classList.add('mui-active');
				tab1Content.style.display = 'block';
				active = 'tab1';
				document.getElementById('text').innerText = '最多支持查询100天内的数据';
			}
		});
		tab2.addEventListener('tap', function() {
			if(!tab2Content.classList.contains('mui-active')) {
				tab1Content.classList.remove('mui-active');
				tab1Content.style.display = 'none';
				tab2Content.classList.add('mui-active');
				tab2Content.style.display = 'block';
				active = 'tab2';
				document.getElementById('text').innerText = '总夜班数 = 夜班小时数/8 ﹢ 节假日班数×1.5';
			}
		});
	}
	function baseSetup() {
		// plus.screen.unlockOrientation(); //解除锁定
		plus.screen.lockOrientation('portrait'); //锁定
		//				plus.navigator.setStatusBarBackground('white');
		//				plus.navigator.setStatusBarStyle('dark');
		var self = plus.webview.currentWebview();
		self.setStyle({
			scrollIndicator: 'none'
		});
		var orientation = window.orientation;
		var screenWidth = window.screen.width;
		var chartHeight = (window.screen.height - 250) / 2.0;

		var lineChart = document.querySelector('.lineChart');
		var rankingChart = document.querySelector('.rankingChart');

		if(orientation == 90 || orientation == -90) { //横屏
			screenWidth = window.screen.height / 2.0 - 5;
			chartHeight = window.screen.width - 64;
			var muiContent = document.querySelector('.mui-content');
			muiContent.classList.add('rotateClass');
			if(window.screen.height < window.screen.width) { //安卓
				screenWidth = window.screen.width / 2.0 - 5;
				chartHeight = window.screen.height - 68;
				muiContent.style.width = window.screen.width + 'px';
			}

			rankingChart.style.marginTop = '0px';
			rankingChart.style.marginLeft = '10px';
		}
		//夜班统计
		lineChart.style.width = screenWidth + 'px';
		lineChart.style.height = chartHeight + 'px';

		//排名
		rankingChart.style.width = screenWidth + 'px';
		rankingChart.style.height = screen_height - chartHeight - 210 + 'px';

		if(orientation == 90 || orientation == -90) { //横屏
			lineChart.style.width = screenWidth - 10 + 'px';
			rankingChart.style.width = screenWidth + 10 + 'px';
		}
		lineChartEl = echarts.init(lineChart);
		rankChartEl = echarts.init(rankingChart);

		var currentDate = new Date();
		var currYear = currentDate.getFullYear();
		var currMonth = currentDate.getMonth() + 1;
		var cQuarter = 1;
		if(currMonth < 4) {
			currYear--;
			quarterStr = '四';
			cQuarter = 4;
		} else if(currMonth < 7) {
			quarterStr = '一';
			cQuarter = 1;
		} else if(currMonth < 10) {
			quarterStr = '二';
			cQuarter = 2;
		} else {
			quarterStr = '三';
			cQuarter = 3;
		}
		titleStr = '第' + quarterStr + '季度'
		if (hasNotPower('2')) {
			getRankData(currYear, cQuarter);
		}

		startBtn = document.getElementById("startDate");
		endBtn = document.getElementById("endDate");
		var timeArr = getStartAndEndTime();
		startTime = timeArr[0];
		startBtn.innerText = startTime;
		endTime = timeArr[1];
		endBtn.innerText = endTime;

		//				while(currentDate.indexOf('/') >= 0)
		//				currentDate = currentDate.replace('/','-');//字符替换
		//				startBtn.innerText = currentDate;

		//查询条按钮监听
		startBtn.addEventListener('tap', function() {
			selectDate(this);
		});
		endBtn.addEventListener('tap', function() {
			selectDate(this);
		});

		getStatisticsData(startBtn.innerText, endBtn.innerText); //mark				
	}

	/*
	 * 获取月个人夜班数、病区平均夜班数
	 * 入参：用户id^科室^年份^季度 例如: "10351^1628^2018^1"
	 * [{"LocNday":"3.1","Month":1,"PerNday":7}]
	 * LocNday:病区夜班平均数
	 * PerNday:个人夜班数
	 */
	function getStatisticsData(cYear, cQuarter) {
		plus.nativeUI.showWaiting('正在查询');
		isStaticRequest = true;
		var starttime = startBtn.innerText;
		var endtime = endBtn.innerText;
		var pdict = {'parr':wardID+'^'+starttime+'^'+endtime+'^'+usercode+'^',nurseid:nurseId}
		var paramDict = {'method':'web.INMArgComm:FindArgHourList','params':JSON.stringify(pdict),'type':'RecQuery'}
		// console.log(JSON.stringify(pdict))
		mui.DHCWebService(paramDict, function(result) {
			//执行成功
			if (result.msgcode != '1') {
				mui.toast(result.msg)
			}
			var arrary = result.data;
			//console.log(JSON.stringify(arrary))
			if(!arrary || arrary.length == 0) {
				arrary = [{
					'HourNurseName': '没有夜班数据',
					'HourTotalTime': '0',
					'HolidayNightNum': '0',
					'TotalNightNum': '0'
				}];
			}
			xAxisData = arrary[0].HourNurseName.split();
			yearNightData = [parseFloat(arrary[0].HourTotalTime).toFixed(2)];
			holidayNightData = [parseFloat(arrary[0].HolidayNightNum).toFixed(2)];
			totalData = [parseFloat(arrary[0].TotalNightNum).toFixed(2)];
			maxA = parseInt(yearNightData[0]);
			maxC = parseInt(totalData[0]);

			prepareNightOptions();
			isStaticRequest = false;
			if(!isRankRequest) {
				plus.nativeUI.closeWaiting();
			}
		}, function(error) {
			mui.toast(error);
			isStaticRequest = false;
			if(!isRankRequest) {
				plus.nativeUI.closeWaiting();
			}
		});
	}

	/*
	 * 获取月病区个人夜班数排行
	 *  入参：科室^年份^季度   例如:"570^2018^1"
	 * [{"Num":1,"PerName":"胡宇凡/李凡"}]
	 */

	function getRankData(cYear, cQuarter) {
		isRankRequest = true;
		var pdict = {'parr':wardID + '^' + cYear + '^' + cQuarter}
		var paramDict = {'method':'web.INMOutInterface:getNurNightShift','params':JSON.stringify(pdict),'type':'MethodNoFilter'}
		// console.log(JSON.stringify(pdict))
		mui.DHCWebService(paramDict, function(result) {
			// console.log(JSON.stringify(result))
			if (result.msgcode != '1') {
				mui.toast(result.msg)
			}
			var arrary = result.data;
			//arrary=[[{"Num":32,"PerName":"徐程菁"},{"Num":28,"PerName":"郎卉馨"},{"Num":23,"PerName":"马澜/管小娥/刘萍"},{"Num":22,"PerName":"沈洁"},{"Num":21,"PerName":"王鹏/李君蕊/朱岩"}],[{"Numhours":288,"PerName":"徐程菁"},{"Numhours":244,"PerName":"郎卉馨"},{"Numhours":216,"PerName":"马澜/管小娥"},{"Numhours":200,"PerName":"刘萍"},{"Numhours":192,"PerName":"沈洁/杨贝/吴翠婷"}]]
			//执行成功
			var keyArr = ['Num', 'Numhours'];
			for(var i = 0; i < arrary.length; i++) {
				var oneData = arrary[i];
				var oneKey = keyArr[i];
				var oneRankXData = [];
				var oneRankYData = [];
				for(var j = 0; j < oneData.length; j++) {
					var oneKeyData = oneData[j];
					oneRankXData[j] = oneKeyData.PerName
					oneRankYData[j] = oneKeyData[oneKey];
				}
				rankXData[i] = oneRankXData;
				rankYData[i] = oneRankYData;
			}
			prepareRankOptions();
			isRankRequest = false;
			if(!isStaticRequest) {
				plus.nativeUI.closeWaiting();
			}
		}, function(error) {
			mui.toast(error);
			isRankRequest = false;
			if(!isStaticRequest) {
				plus.nativeUI.closeWaiting();
			}
		});
	}

	function prepareNightOptions() {
		var nightImage = 'image:images/line-color.png';
		var seriesType = 'line';
		var labelY = 10;
		if(nightShap == '柱状图') {
			nightImage = 'image:images/line-color.png';
			seriesType = 'bar';
			labelY = -12;
		}
		var hourImage, timesImage;
		if(nightUnitShap == '(小时)') {
			hourImage = 'image://images/hour.png';
			timesImage = 'image://images/times_gray.png';
		} else {
			hourImage = 'image://images/hour_gray.png';
			timesImage = 'image://images/times.png';
		}
		var colors = ['#5793f3', '#d14a61', '#24AF96'];

		var optionNight = {
			color: colors,
			tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'cross'
				}
			},
			title: {
				//						text: titleStr + '我的夜班数统计',//标题
				text: '我的夜班数及节假日夜班数',
				x: 'center',
				textStyle: {
					fontSize: 15, //标题字号
					fontWeight: 400,
					color: '#323232',
				},
				bottom: 0
			},
			//					legend: { data: legendData, right: 50, top: 25, left: 50 },//筛选按钮的位置
			grid: {
				left: 15,
				right: 15,
				bottom: 25, //第一个的高度
				top: 32, //第一个居上多少
				containLabel: true, //坐标系的位置
				backgroundColor: 'grey',
			},
			xAxis: {
				type: 'category',
				axisTick: {
					alignWithLabel: true
				},
				boundaryGap: true,
				data: xAxisData
			},
			yAxis: [{
					type: 'value',
					name: '全年夜班小时数',
					min: 0,
					max: maxA,
					position: 'left',
					axisLine: {
						lineStyle: {
							color: colors[0]
						}
					},
					axisLabel: {
						formatter: '{value} h'
					},
				},
				{
					type: 'value',
					name: '节假日',
					min: 0,
					max: maxC,
					position: 'right',
					offset: -10,
					axisLine: {
						lineStyle: {
							color: colors[1]
						}
					},
					axisLabel: {
						formatter: '{value} 个'
					},
					//          				nameGap:0
				},
				{
					type: 'value',
					name: '总计',
					min: 0,
					max: maxC,
					position: 'right',
					offset: 40,
					axisLine: {
						lineStyle: {
							color: colors[2]
						}
					},
					axisLabel: {
						formatter: '{value} 个'
					},
				}
			],
			series: [{
					name: '全年夜班小时数',
					type: 'bar',
					label: {
						normal: {
							show: true,
							position: [15, -15],
							formatter: '{c|{c}}',
							rich: {
								c: {
									fontSize: 12,
								}
							}
						}
					},
					data: yearNightData //字符串转成数组
				},
				{
					name: '节假日夜班个数',
					type: 'bar',
					yAxisIndex: 1,
					label: {
						normal: {
							show: true,
							position: [20, -15],
							formatter: '{c|{c}}',
							rich: {
								c: {
									fontSize: 12,
								}
							}
						}
					},
					data: holidayNightData
				},
				{
					name: '总夜班数',
					type: 'bar',
					yAxisIndex: 2,
					label: {
						normal: {
							show: true,
							position: [20, -15],
							formatter: '{c|{c}}',
							rich: {
								c: {
									fontSize: 12,
								}
							}
						}
					},
					data: totalData
				}
			]
		};
		updateUIs(optionNight, lineChartEl);
	}

	function prepareRankOptions() {
		var rankImage = 'image://images/bar-color.png';
		var seriesType = 'line';
		if(rankShap == '柱状图') {
			rankImage = 'image://images/line-color.png';
			seriesType = 'bar';
		}
		var hourImage, timesImage;
		var xData = [];
		var yData = [];
		if(rankUnitShap == '(小时)') {
			hourImage = 'image://images/hour.png';
			timesImage = 'image://images/times_gray.png';
			xData = rankXData[1];
			yData = rankYData[1];
		} else {
			hourImage = 'image://images/hour_gray.png';
			timesImage = 'image://images/times.png';
			xData = rankXData[0];
			yData = rankYData[0];
		}
		var optionRank = {
			color: '#24AF96',
			tooltip: {
				trigger: 'axis',
				axisPointer: { // 坐标轴指示器，坐标轴触发有效
					type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
				}
			},
			title: {
				text: titleStr + '本科室夜班数排行榜',
				x: 'center',
				textStyle: {
					fontSize: 15,
					fontWeight: 400,
					color: '#323232'
				},
				bottom: 0
			},
			grid: {
				left: 30,
				right: 30,
				bottom: 30,
				top: 30,
				containLabel: true
			},
			toolbox: {
				top: -5,
				right: 8,
				itemSize: 23,
				feature: {
					myTool1: {
						show: true,
						title: ' ',
						icon: timesImage,
						onclick: rankTimesBtnClicked
					},
					myTool2: {
						show: true,
						title: ' ',
						icon: hourImage,
						onclick: rankHourBtnClicked
					},
					myTool3: {
						show: true,
						title: ' ',
						icon: rankImage,
						onclick: rankBtnClicked
					}
				}
			},
			xAxis: {
				type: 'category',
				boundaryGap: true,
				data: xData,
				axisLabel: {
					interval: 0, //横轴信息全部显示  
					rotate: 20, //-30度角倾斜显示
					padding: [0, -15, -10, 0],
				},
				axisLine: {
					lineStyle: {
						color: '#e98f36'
					}
				},
			},
			yAxis: {
				type: 'value',
				name: rankUnitShap,
				nameGap: 5,
				axisLine: {
					lineStyle: {
						color: '#1195db',
						height: 5
					}
				},

			},
			series: [{
				type: seriesType,
				label: {
					normal: {
						show: true,
						position: [15, -15],
						formatter: '{c|{c}}',
						padding: 0,
						rich: {
							c: {
								fontSize: 12,
							}
						}
					}
				},
				data: yData
			}]
		};
		updateUIs(optionRank, rankChartEl);
	}

	//夜班统计点击方法
	function nightBtnClicked() {
		if(nightShap == '折线图') {
			nightShap = '柱状图';
		} else {
			nightShap = '折线图';
		}
		prepareNightOptions();
	}
	//夜班统计查询次数方法
	function nightTimesBtnClicked() {
		nightUnitShap = '(个)';
		prepareNightOptions();
	}
	//夜班统计查询小时数方法
	function nightHourBtnClicked() {
		nightUnitShap = '(小时)';
		prepareNightOptions();
	}
	//排名统计切换柱状图和折线图方法
	function rankBtnClicked() {
		if(rankShap == '折线图') {
			rankShap = '柱状图';
		} else {
			rankShap = '折线图';
		}
		prepareRankOptions();
	}
	//夜班排名查询次数方法
	function rankTimesBtnClicked() {
		rankUnitShap = '(个)';
		prepareRankOptions();
	}
	//夜班排名查询小时数方法
	function rankHourBtnClicked() {
		rankUnitShap = '(小时)';
		prepareRankOptions();
	}

	function updateUIs(optionNight, chartEl) {
		chartEl.setOption(optionNight);
	}

	//tab2content
	$(function() {
		var s = $("input[name='check']");
		s.each(function(i) {
			if(this.checked) {
				nurTypeStr += this.value + ',';
			}
			$(this).click(function() {
				if(this.checked) {
					nurTypeStr = nurTypeStr + this.value + ',';
					// console.log('护士类型:', nurTypeStr);
				} else {
					var reg = new RegExp(this.value + ',', "g");
					nurTypeStr = nurTypeStr.replace(reg, '');
					// console.log('护士类型', nurTypeStr);
				}
				startT = startBtn.innerText;
				endT = endBtn.innerText;
				locPage = 0;
				var pageNumber = document.getElementById('pageNum');
				pageNumber.innerText = '第' + (locPage+1) + '页';
				requestRankData(startT, endT, nurTypeStr);
			});
		});
	})

	//科室统计
	function requestRankData(starttime, endtime, nurType) {
		if(nurType == '') {
			updatetab2UIs(null);
			return;
		}
		// if(maxRole!= ''&&parseInt(maxRole) > 4) {
		// 	mui.toast('护士角色无权限');
		// 	return;
		// }
		if(starttime > endtime) {
			mui.toast('时间选择不正确');
			return;
		}
		plus.nativeUI.showWaiting('正在查询');
		//parr 病区^开始日期^结束日期^姓名工号(搜索用的)^类型(多个用,分割)
		var pdict = {'parr':wardID+'^'+starttime+'^'+endtime+'^^'+nurType,
			nurseid:nurseId,start:(locPage*pageLimit),limit:pageLimit}
		var paramDict = {'method':'web.INMArgComm:FindArgHourList','params':JSON.stringify(pdict),'type':'RecQuery'}
		// console.log(JSON.stringify(pdict))
		mui.DHCWebService(paramDict, function(result) {
		//postHttpRequest(xmlStr2, 'nurse.personal.nightstat', function(result) {
			plus.nativeUI.closeWaiting();
			if (result.msgcode != '1') {
				mui.toast(result.msg)
			}
			var resultArray = result.data;
			// console.log(JSON.stringify(resultArray));
			updatetab2UIs(resultArray);
		}, function(error) {
			mui.toast(error);
			plus.nativeUI.closeWaiting();
		});
	}

	function updatetab2UIs(dataArr) {
		var tableBody = document.getElementById('tableBody');
		if(dataArr == null) {
			tableBody.innerHTML = '';
			return;
		}
		if(dataArr.length == 0) {
			tableBody.innerHTML = '';
			mui.toast('无相应数据');
			return;
		}
		html = ''
		for(var i = 0; i < dataArr.length; i++) {
			var oneData = dataArr[i];
			var color = '',NurTypeDesc = oneData.NurTypeDesc
			if(NurTypeDesc == '正式护士') {
				color = 'black'
			} else if(NurTypeDesc == '实习护士') {
				color = 'red'
			} else if(NurTypeDesc == '进修护士') {
				color = 'palevioletred'
			} else if(NurTypeDesc == '护理员') {
				color = 'deeppink'
			} else if(NurTypeDesc == '培训护士') {
				color = '07502A'
			}
			html += '<tr style="font-size: 10px; text-align: center;">'+
				'<td nowrap="nowrap" style="color:'+color+';">' + NurTypeDesc + '</td>'+
				'<td nowrap="nowrap" style="font-size: 11px;">' + oneData.HourPerId + '</td>'+
				'<td nowrap="nowrap" style="width:12%;">' + oneData.HourNurseName +'</td>'+
				'<td>' + oneData.HourWardDesc + '</td>'+
				'<td class="yearHours">' + oneData.HourTotalTime + '</td>'+
				'<td style="width:11.5%;font-size: 13px;">' + oneData.HolidayNightNum + '</td>'+
				'<td style="width:10.3%;color:red;font-size: 13px;">' + oneData.TotalNightNum + '</td></tr>';
		}
		tableBody.innerHTML = html;
		plus.nativeUI.closeWaiting();
	};
	document.getElementById('nextPage').addEventListener('tap', function() {
		locPage = locPage + 1;
		startT = startBtn.innerText;
		endT = endBtn.innerText;
		requestRankData(startT, endT, nurTypeStr);
		var pageNumber = document.getElementById('pageNum');
		pageNumber.innerText = '第' + (locPage + 1) + '页';
	});

	document.getElementById('lastPage').addEventListener('tap', function() {
		if(locPage == 0) {
			mui.toast('已经是第一页');
			return;
		}
		locPage = locPage - 1;
		startT = startBtn.innerText;
		endT = endBtn.innerText;

		requestRankData(startT, endT, nurTypeStr);
		var pageNumber = document.getElementById('pageNum');
		pageNumber.innerText = '第' + (locPage +1) + '页';

	});

	function selectDate(btn) {

		var dDate = new Date();
		var minDate = new Date();
		minDate.setFullYear(2007, 1, 1);
		var maxDate = new Date();
		maxDate.setFullYear(2099, 12, 31);
		plus.nativeUI.pickDate(function(e) {
			var d = e.date;
			var syear = d.getFullYear();
			var smonth = d.getMonth() + 1;
			var sday = d.getDate();
			var datestr = outDays(syear, smonth, sday);
			if(btn.id == "startDate") {
				var starttime = d.getTime();
				var endDate = getDateWithStr(endBtn.innerText);
				var endtime = endDate.getTime();
				console.log(datestr);
				btn.innerHTML = datestr;
				if(starttime > endtime) {
					mui.toast('请选择结束时间');
					selectDate(endBtn);
				} else {
					if(active == 'tab1') {
						getStatisticsData(startBtn.innerText, endBtn.innerText);
					} else {
						requestRankData(startBtn.innerText, endBtn.innerText, nurTypeStr);
					}
				}
			} else if(btn.id == "endDate") {
				var startDate = getDateWithStr(startBtn.innerText);
				var starttime = startDate.getTime();
				var endtime = d.getTime();
				if(starttime > endtime) {
					mui.alert('结束时间不能早于开始时间', '提示', '明白', selectDate(btn));
				} else {
					btn.innerHTML = datestr;
					if(active == 'tab1') {
						getStatisticsData(startBtn.innerText, endBtn.innerText);
					} else {
						requestRankData(startBtn.innerText, endBtn.innerText, nurTypeStr);
					}
				}
			}
		}, function(e) {

		}, {
			title: "请选择日期",
			date: dDate,
			minDate: minDate,
			maxDate: maxDate
		});
	}
	function hasNotPower(power){
		if (roles == ''  ) { //护理部和护士长角色有审批中心
			return false
		}
		var arr = roles.split(',')
		var has = false
		for (var i = 0; i < arr.length; i++) {
			if (arr[i] == '') {
				continue
			}
			if (arr[i]+'' != power) {
				has = true
				break
			}
		}
		return has
	}
	function hasPower(power){
		if (roles == ''  ) { //护理部和护士长角色有审批中心
			return false
		}
		var arr = roles.split(',')
		var has = false
		for (var i = 0; i < arr.length; i++) {
			if (arr[i] == '') {
				continue
			}
			if (arr[i]+'' == power) {
				has = true
				break
			}
		}
		return has
	}
})()